<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\ScenicSpot;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserScenicSpot;

class UserScenicSpotService
{
    /**
     * 景点打卡
     *
     * @param $spotId
     * @return void
     */
    public static function add($spotId, $image)
    {
        $spot = ScenicSpot::where('id', $spotId)->first();

        if (!$spot) {
            throw new \Exception('不存在的景点');
        }

        $spot->views++;
        $spot->save();

        UserProfile::where('user_id', get_user_id())->increment('scenic_spot_view_count');

        UserScenicSpot::insert([
            'user_id' => get_user_id(),
            'scenic_spot_id' => $spotId,
            'image' => $image,
            'created_time' => date('Y-m-d H:i:s'),
            'sort' => $spot->views
        ]);
    }

    /**
     * 打卡记录
     *
     * @param $page
     * @param $length
     * @return false[]|float[]
     */
    public static function list($page = 1, $length = 10)
    {
        $offset = ($page - 1) * $length;
        $query = UserScenicSpot::select(['id', 'scenic_spot_id', 'created_time', 'image', 'sort'])->where('user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('created_time')->get()->toArray();

        $scenicSpotIds = array_column($list, 'scenic_spot_id');
        $scenicSpots = ScenicSpot::select(['id', 'name', 'thumb'])->whereIn('id', $scenicSpotIds)->get()->keyBy('id')->toArray();

        foreach ($list as $key=>$item) {
            $spot = $scenicSpots[$item['scenic_spot_id']] ?? [];
            $spot['thumb'] = full_url($spot['thumb'] ?? '');
            $list[$key]['image'] = full_url($item['image']);
            $list[$key]['scenic_spot'] = $spot;
        }

        return Page::wrap($totalCount, $page, $length, $list);

    }
}